package cn.quevo.core.file.text;

import cn.quevo.core.exception.CheckParamsException;
import cn.quevo.core.file.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 文本文件读取
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018/08/01 11:19:35
 * @Copyright 东方浩星（北京）传媒科技有限公司版权所有.All Rights Reserved.
 */
public class Text {
    private final static Logger log = LoggerFactory.getLogger(Text.class);

    public static String getContent(File file) {
        if (file == null || !file.exists() || !file.isFile()) {
            throw new CheckParamsException(6021, "文件不存在");
        }
        String fileExt = FileUtils.getFileSuffix(file.getName());
        if (!".txt".equalsIgnoreCase(fileExt)) {
            throw new CheckParamsException(6020, "文件非文本格式文档");
        }
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file));) {
            String line = "";
            StringBuilder content = new StringBuilder("");
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6022, "文件不存在");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6023, "文件读取失败");
        }
    }

    public static String getContent(InputStream inputStream,String fileExt) {
        fileExt = FileUtils.getFileSuffix(fileExt);
        if (!".pdf".equalsIgnoreCase(fileExt)) {
            throw new CheckParamsException(6020, "文件非PDF格式文档");
        }
        int len = -1;
        byte[] buf = new byte[1024];
        try {
            StringBuilder content = new StringBuilder("");
            while ((len = inputStream.read(buf)) != -1) {
                content.append(new String(buf, 0, len));
            }
            return content.toString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6023, "文件读取失败");
        }
    }
}
